<template>
  <div class="min-h-screen bg-[#FFFFFF] flex flex-col md:flex-row">
    <!-- 左侧导航栏 -->
    <Nav class="md:flex-shrink-0 w-full md:w-auto"></Nav>

    <!-- 右侧主体内容 -->
    <div class="flex-1 h-screen flex flex-col">
      <!-- 顶部标题区域 - 固定不滚动 -->
      <div class="p-4 md:p-8 pb-2 md:pb-4 flex-none">
        <h1 class="text-lg md:text-xl font-semibold text-gray-800 mb-1">智测 · 创建测试</h1>
        <p class="text-xs md:text-sm text-gray-500">根据学生知识点掌握情况，智能推荐最适合的试题组合</p>
      </div>

      <div class="flex-1 overflow-y-auto px-4 md:px-8">
      <!-- 筛选条件区域 -->
      <div class="bg-white rounded-xl p-4 md:p-6 shadow-sm mb-6 border border-gray-100">
        <!-- 教材选择 -->
        <div class="mb-6">
          <h3 class="text-sm text-gray-900 mb-3">教材选择：</h3>
          <el-radio-group v-model="selectedTextbook.id">
            <el-radio 
              :label="selectedTextbook.id" 
              border 
              class="!rounded-lg">
              {{ selectedTextbook.label }}
            </el-radio>
          </el-radio-group>
          <p class="text-xs md:text-sm text-gray-400 pt-4">教材版本可以在学生中心进行修改</p>
        </div>

        <!-- 年级选择 -->
        <div class="mb-6">
          <h3 class="text-sm text-gray-900 mb-3">年级选择：</h3>
          <div class="flex flex-wrap gap-2 md:gap-3">
            <el-button 
              v-for="grade in gradersList" 
              :key="grade.value"
              :class="selectedGrade === grade.value ? 'is-active !bg-blue-50 !text-blue-500 !border-blue-200' : ''"
              @click="selectedGrade = grade.value"
              class="!rounded-full !text-xs md:!text-sm !px-2 md:!px-3 !py-1 md:!py-2 mb-2">
              {{ grade.label }}
            </el-button>
          </div>
        </div>

        <!-- 学期选择 -->
        <div class="mb-6">
          <h3 class="text-sm text-gray-900 mb-3">学期选择：</h3>
          <div class="flex gap-3">
            <el-button 
              v-for="term in terms" 
              :key="term.value"
              :class="selectedTerm === term.value ? 'is-active !bg-blue-50 !text-blue-500 !border-blue-200' : ''"
              @click="selectedTerm = term.value"
              class="!rounded-full !text-xs md:!text-sm !px-3 !py-1 md:!py-2">
              {{ term.label }}
            </el-button>
          </div>
        </div>

        <!-- 测试类型 -->
        <div class="mb-6">
          <h3 class="text-sm text-gray-900 mb-3">测试类型：</h3>
          <div class="flex flex-col md:flex-row gap-3 md:gap-6">
            <div 
              v-for="type in testTypes" 
              :key="type.value"
              @click="selectedTestType = type.value"
              :class="[
                'p-3 md:p-4 rounded-xl cursor-pointer transition-all border-2 mb-2 md:mb-0',
                selectedTestType === type.value ? 'border-blue-500 bg-blue-50' : 'border-gray-100 hover:border-gray-200'
              ]">
              <div class="flex items-center justify-between mb-2">
                <span class="font-medium text-sm md:text-base">{{ type.label }}</span>
                <el-icon :class="selectedTestType === type.value ? 'text-blue-500' : 'text-gray-400'">
                  <component :is="type.icon" />
                </el-icon>
              </div>
              <p class="text-xs md:text-sm text-gray-500">{{ type.description }}</p>
            </div>
          </div>
        </div>

        <!-- 知识点选择 -->
        <div class="mb-6">
          <h3 class="text-sm text-gray-900 mb-3">知识点：</h3>
        
          <!-- 分类折叠面板 -->
          <el-collapse v-model="activeCategories" class="!border-none">
            <el-collapse-item 
              v-for="category in knowledgeCategories" 
              :key="category.id"
              :title="category.name"
              :name="category.id"
              class="!border-b border-gray-100 last:!border-none">
             <!-- 修改全选框部分的代码 -->
              <template #title>
                <div class="flex items-center justify-between w-full pr-4">
                  <div class="flex items-center gap-2">
                    <div 
                      class="flex items-center z-10 cursor-pointer" 
                      @click.stop="handleCheckboxClick(category)">
                      <el-checkbox
                        v-model="category.allSelected"
                        class="!mr-1"
                        :disabled="false">
                      </el-checkbox>
                    </div>
                    <FolderOutlined style="color: rgb(255,214,89); fill: rgb(255,214,89); width: 16px; height: 16px;" />
                    <span class="text-xs md:text-sm">{{ category.name }}</span>
                  </div>
                  <span class="text-xs text-gray-400">
                    已选 {{ category.points.filter(p => p.selected).length }}/{{ category.points.length }}
                  </span>
                </div>
              </template>
              
              <div class="flex flex-wrap gap-2 pt-2">
                <el-tag
                  v-for="point in category.points"
                  :key="point.value"
                  class="!rounded-full !px-3 md:!px-4 !py-1 md:!py-1.5 mb-2 !text-xs"
                  :class="point.selected ? '!bg-blue-500 !border-blue-500 !text-white' : ''"
                  @click="togglePoint(point)"
                  :effect="point.selected ? 'dark' : 'plain'">
                  {{ point.label }}
                </el-tag>
              </div>
            </el-collapse-item>
          </el-collapse>
          
          <div class="flex flex-col md:flex-row justify-between items-start md:items-center mt-4 text-xs md:text-sm">
            <p class="text-gray-400 mb-2 md:mb-0">我们将根据当前知识点的掌握情况，生成最适合的测试题目</p>
            <el-button type="primary" link @click="expandAll" class="!text-xs md:!text-sm">
              {{ isAllExpanded ? '收起全部' : '展开全部' }}
            </el-button>
          </div>
        </div>

        <!-- 题目数量 -->
        <div>
          <h3 class="text-sm text-gray-900 mb-3">题目数量</h3>
          <div class="flex gap-3">
            <el-button 
              v-for="count in questionCounts" 
              :key="count"
              :class="selectedCount === count ? 'is-active !bg-blue-50 !text-blue-500 !border-blue-200' : ''"
              @click="selectedCount = count"
              class="!rounded-full !text-xs md:!text-sm !px-3 !py-1 md:!py-2">
              {{ count }}题
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 底部操作按钮 -->
      <div class="pt-4 pb-6 flex-none flex justify-center">
        <el-button 
          type="primary" 
          class="!w-full md:!w-40 !rounded-full !bg-gradient-to-r from-blue-500 to-blue-600 border-none hover:from-blue-600 hover:to-blue-700"
          @click="handleCreate">
          创建智测
        </el-button>
      </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import Nav from "@/components/nav/index.vue";
import { ref, computed ,onMounted, watch} from 'vue';
import { Monitor, Document } from '@element-plus/icons-vue';
import { FolderOutlined, FileOutlined } from '@/components/icons/index.js';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getDefaultChild } from '@/utils/auth.js';
import { getGradesList,getGradesV2List,getChapters,saveSmartPaper } from '@/api/common.js';
import { useAnalysisStore } from '@/stores/analysis'


// 教材版本
const selectedTextbook = ref({
  label: '人教版',
  id: 11740
});
// 
const terms = [
  { label: '上学期', value: 1 },
  { label: '下学期', value: 2 }
];
const selectedTerm = ref(1);

const gradersList = ref([]);

const handGradesList = async () => {
  try {
    const res = await getGradesList();
    // 转换数据结构
    gradersList.value = res.map(item => ({
      label: item.gradeName,
      value: item.grade
    }));
    if (gradersList.value.length > 0) {
      selectedGrade.value = gradersList.value[0].value;
    }
    return;
  } catch (error) {
    console.error('获取年级列表失败', error.message);
    ElMessage.error('获取年级失败');
  }
};

const selectedGrade = ref(1);

// 获取年级信息
const gradersListV2 = ref([]);
const handGradesV2List = async () => {
  try {
    const res = await getGradesV2List({
        versionId: selectedTextbook.value.id 
      });
    gradersListV2.value = res
    return;
  } catch (error) {
    console.error('获取年级列表失败', error.message);
    ElMessage.error('获取年级失败');
  }
};

const bookId = ref(262573);

const currentGradeTermData = computed(() => {
  if (!gradersListV2.value.length) return null;
  return gradersListV2.value.find(
    item => item.grade === selectedGrade.value && item.termType === selectedTerm.value
  );
});


// 测试类型
const testTypes = [
  {
    label: '能力评测',
    value: 1,
    icon: Monitor,
    description: '全面评估学生各项能力水平'
  },
  // {
  //   label: '单元测试',
  //   value: 2,
  //   icon: Document,
  //   description: '针对性测试知识点掌握情况'
  // }
];

const selectedTestType = ref(1);

// 题目数量选项
const questionCounts = [10, 20, 30];
const selectedCount = ref(10);

// 知识点分类
const knowledgeCategories = ref([]);

// 当前展开的分类
const activeCategories = ref([]);

const handelKnowledgeCategories = async () => {
  try {
    const res = await getChapters({
      bookId: bookId.value,
    });
    
    // 确保 res 是数组，如果不是则转换为数组
    const dataArray = Array.isArray(res) ? res : [res];
    
    knowledgeCategories.value = dataArray.map(item => {
      // 如果子类为空，则添加一个"全部"选项
      const points = item.children && Array.isArray(item.children) && item.children.length > 0
        ? item.children.map(point => ({
            label: point.name,
            value: point.id,
            selected: false
          }))
        : [{
            label: '全部',
            value: item.id,  // 使用父级id
            selected: false
          }];
      
      return {
        id: item.id,
        name: item.name,
        points,
        allSelected: false // 添加全选状态
      };
    });

    return;
  } catch (error) {
    // console.error('获取知识点失败', error.message);
    ElMessage.error('获取知识点失败');
  }
};

// 添加新的处理方法
const handleCheckboxClick = (category) => {
  category.allSelected = !category.allSelected;
  toggleAllPoints(category);
};

// 修改原有的 toggleAllPoints 方法
const toggleAllPoints = (category) => {
  const newSelectedState = category.allSelected;
  category.points.forEach(point => {
    point.selected = newSelectedState;
  });
};

// 是否全部展开
const isAllExpanded = computed(() => {
  return activeCategories.value.length === knowledgeCategories.value.length;
});

// 展开/收起全部
const expandAll = () => {
  if (isAllExpanded.value) {
    activeCategories.value = [];
  } else {
    activeCategories.value = knowledgeCategories.value.map(c => c.id);
  }
};

// 切换知识点选择状态（改为单选）
const togglePoint = (point) => {
  // 先取消所有知识点的选中状态（多选）
  // knowledgeCategories.value.forEach(category => {
  //   category.points.forEach(p => {
  //     p.selected = false;
  //   });
  // });
  // // 再选中当前点击的知识点
  // point.selected = true;

  // 直接切换当前知识点的选中状态（单选）
  point.selected = !point.selected;
};

const analysisStore = useAnalysisStore()
// 创建测试
const router = useRouter();
const handleCreate = async () => {
  try {
   // 获取选中的知识点（单选，只取第一个选中的值）
   const selectedPoints = knowledgeCategories.value
      .flatMap(category => category.points)
      .filter(point => point.selected)
      .map(point => point.value);

    // 检查是否选择了知识点
    // if (!selectedPoint) {
    //   ElMessage.warning('请选择一个知识点');
    //   return;
    // }

    // 构建请求参数
    const params = {
      version_id: selectedTextbook.value.id,
      grade: selectedGrade.value,
      term_type: selectedTerm.value,
      type: selectedTestType.value,
      chapter_id: selectedPoints.length > 0 ? selectedPoints : null, // 如果有选中则传数组，否则传 null
      question_total: selectedCount.value,
      book_id: bookId.value,
      subject_id: 3,
    };

    const res = await saveSmartPaper(params);
    console.log(res.id);
    // 检查响应数据是否包含有效的id (修复语法错误，移除多余的文字)
    if (!res?.id) {
      throw new Error('创建失败，未获取到测试ID');
    }

    // 保存完整的响应数据到 store
    analysisStore.setPaperData(res)

    ElMessage.success('创建成功！');
    // 直接跳转，不带查询参数
    return router.push('/analysis/success');

  } catch (error) {
    ElMessage.error(error.message || '创建失败，请重试');
  }
};

onMounted(async () => {
  await handGradesList();
  await handGradesV2List();
  const child = getDefaultChild();
  selectedTextbook.value.id = child.version_id;
  selectedTextbook.value.label = child.version_name;
  
  // 初始化时执行一次数据匹配
  if (currentGradeTermData.value) {
    bookId.value = currentGradeTermData.value.bookId;
    handelKnowledgeCategories();
  }
});

// 添加 watch 来监听子项的选中状态，自动更新全选状态
watch(knowledgeCategories, () => {
  knowledgeCategories.value.forEach(category => {
    // 如果所有子项都被选中，则全选也被选中
    category.allSelected = category.points.every(point => point.selected);
  });
}, { deep: true });

// 添加 watch 监听
watch([selectedGrade, selectedTerm], async () => {
  if (currentGradeTermData.value) {
    console.log('匹配到的数据：', currentGradeTermData.value);
    // 这里可以处理匹配到的数据
    bookId.value = currentGradeTermData.value.bookId;
    // 重新获取知识点
    handelKnowledgeCategories();
  }
  console.log('bookId:', bookId.value);
});
</script>

<style scoped>
.el-button.is-active {
  font-weight: 500;
}

.el-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.el-tag:hover {
  transform: translateY(-1px);
}

:deep(.el-collapse-item__header) {
  font-size: 0.875rem;
  color: #374151;
  font-weight: 500;
  padding: 12px 0;
}

:deep(.el-collapse-item__content) {
  padding-bottom: 12px;
}

:deep(.el-collapse) {
  --el-collapse-border-color: transparent;
}
</style>